package com.zyf.EasyNet.app.config;

/**
 * @first_author zyflzz
 * @gmt_created 2022/4/19
 * @gmt_modified 2022/4/19
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 这个类是 Session 的 Configuration
 */
@Configuration
@EnableSpringHttpSession
public class SpringHttpSessionConfigurer {

    /**
     * 读写 cookies 中的 SessionId 信息
     *
     * @return CookieSerializer 序列化的用户信息
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("JSESSIONID");
        // 用正则表达式配置匹配的域名，采用非贪婪模式，可以兼容 localhost、127.0.0.1 等各种场景
        serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
        serializer.setCookiePath("/");
        serializer.setUseHttpOnlyCookie(false);
        // 设置 cookie 生命周期为2天
        serializer.setCookieMaxAge(48 * 60 * 60);
        return serializer;
    }

    /**
     * Session 信息在服务器上的存储仓库
     *
     * @return MapSessionRepository 存储仓库
     */
    @Bean
    public MapSessionRepository sessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }


}
